package cn.iocoder.yudao.module.infra.api.zip.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import jakarta.validation.constraints.NotBlank;
import java.util.Map;

/**
 * 文件下载项
 *
 * @author 芋道源码
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class FileDownloadItem {

//    @Schema(description = "文件URL", requiredMode = Schema.RequiredMode.REQUIRED, example = "https://example.com/file.jpg")
    @NotBlank(message = "文件URL不能为空")
    private String url;

//    @Schema(description = "ZIP内文件名", example = "image.jpg")
    private String fileName;

//    @Schema(description = "ZIP内文件路径（包含目录）", example = "images/2024/image.jpg")
    private String filePath;

//    @Schema(description = "文件描述", example = "用户头像")
    private String description;

//    @Schema(description = "自定义请求头")
    private Map<String, String> headers;

//    @Schema(description = "下载超时时间（秒）", example = "30")
    private Integer timeout;

//    @Schema(description = "最大文件大小（MB）", example = "50")
    private Integer maxSizeMB;

//    @Schema(description = "是否必需文件（false时下载失败会跳过）", example = "true")
    private Boolean required = true;

//    @Schema(description = "重试次数", example = "3")
    private Integer retryCount = 0;

    /**
     * 获取最终的文件名
     */
    public String getFinalFileName() {
        if (fileName != null && !fileName.trim().isEmpty()) {
            return fileName;
        }
        
        // 从URL中提取文件名
        String extractedName = url.substring(url.lastIndexOf('/') + 1);
        
        // 移除查询参数
        int queryIndex = extractedName.indexOf('?');
        if (queryIndex > 0) {
            extractedName = extractedName.substring(0, queryIndex);
        }
        
        // 如果没有扩展名，添加默认扩展名
        if (!extractedName.contains(".")) {
            extractedName += ".file";
        }
        
        return extractedName;
    }

    /**
     * 获取最终的文件路径
     */
    public String getFinalFilePath() {
        if (filePath != null && !filePath.trim().isEmpty()) {
            return filePath;
        }
        
        return getFinalFileName();
    }

    /**
     * 获取有效的超时时间
     */
    public int getEffectiveTimeout(int defaultTimeout) {
        return timeout != null && timeout > 0 ? timeout : defaultTimeout;
    }

    /**
     * 获取有效的最大文件大小
     */
    public int getEffectiveMaxSizeMB(int defaultMaxSize) {
        return maxSizeMB != null && maxSizeMB > 0 ? maxSizeMB : defaultMaxSize;
    }

    /**
     * 是否为必需文件
     */
    public boolean isRequired() {
        return required != null ? required : true;
    }

    /**
     * 获取有效的重试次数
     */
    public int getEffectiveRetryCount() {
        return retryCount != null && retryCount >= 0 ? retryCount : 0;
    }

}
